<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <!-- <template slot="menuLeft">
        <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          v-if="permission.pos_store_delete"
          @click="handleDelete"
          >删 除
        </el-button>
      </template> -->
      <!-- <template slot="menuRight">
        <el-button
          type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          v-if="permission.pos_store_import"
          @click="handleImport"
          >导入
        </el-button>
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permission.pos_store_export"
          @click="handleExport"
          >导出
        </el-button>
      </template> -->
      <template slot-scope="{ row }" slot="storeStatus">
        <el-switch
          :active-value="0"
          :inactive-value="1"
          v-model="row.storeStatus"
          @change="handleSwitch(row)"
        >
        </el-switch>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button
          icon="el-icon-menu"
          size="small"
          type="text"
          v-if="permissionList.editBtn"
          @click.stop="handleStore(row)"
          >管理门店</el-button
        >
        <el-button
          icon="el-icon-edit"
          size="small"
          type="text"
          v-if="permissionList.editBtn"
          @click.stop="handlePassword(row)"
          >修改密码</el-button
        >
      </template>
    </avue-crud>
    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
    <!-- 修改密码 -->
    <el-dialog
      title="修改密码"
      append-to-body
      width="550px"
      v-if="passwordShow"
      :visible.sync="passwordShow"
      :before-close="handlePassClose"
    >
      <template>
        <passForm :passForm="passForm" ref="toPassForm" />
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button
          icon="el-icon-check"
          size="small"
          type="primary"
          v-preventClick
          @click.stop="getPassUpdate"
          >提 交</el-button
        >
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  addRpi,
  updateRpi,
  remove,
  changeStoreStatus,
  getUpdatePwd,
} from "@/api/rb-merchant/posStore/pos_store";
import { getRegion } from "@/api/system/dict";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
import { isMobile } from "@/util/validate";
import passForm from "@/components/rb-service/pass-form";

export default {
  components: {
    passForm,
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入联系方式"));
      } else if (!isMobile(value)) {
        callback(new Error("手机号码不正确！"));
      } else {
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        // height: "auto",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        searchMenuSpan: 6,
        columnBtn: false,
        // menuWidth: "300",
        column: [
          {
            label: "主键",
            prop: "id",
            type: "input",
            //sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "门头名称",
            prop: "rpiNo",
            type: "select",
            display: false,
            hide: true,
            overHidden: true,
          },
          // {
          //   label: "用户编号",
          //   prop: "userNo",
          //   type: "input",
          //   //sortable: true,
          //   search: true,
          //   display: false,
          // },
          {
            label: "门店编号",
            prop: "rpsNo",
            type: "input",
            //sortable: true,
            slot: true,
            display: false,
            overHidden: true,
            width:110,
          },
          {
            label: "门店名称",
            prop: "rpsName",
            type: "input",
            search: true,
            span: 24,
            rules: [
              {
                required: true,
                message: "请输入门店名称",
                trigger: "blur",
              },
            ],
            overHidden: true,
            width:180
          },
          {
            label: "创建日期",
            prop: "produceTime",
            type: "input",
            //sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            overHidden: true,
            width:140
          },
          //   {
          //     label: "省份",
          //     prop: "provinceName",
          //     slot: true,
          //     display: false,
          //     overHidden:true,
          //   },
          //   {
          //     label: "地市",
          //     prop: "cityName",
          //     slot: true,
          //     display: false,
          //     overHidden:true,
          //   },
          //   {
          //     label: "区县",
          //     prop: "areaName",
          //     slot: true,
          //     display: false,
          //     overHidden:true,
          //   },
          {
            label: "省份",
            prop: "province",
            slot: true,
            display: false,
            hide: true,
            overHidden: true,
          },
          {
            label: "地市",
            prop: "city",
            slot: true,
            display: false,
            hide: true,
            overHidden: true,
          },
          {
            label: "区县",
            prop: "area",
            slot: true,
            display: false,
            hide: true,
            overHidden: true,
          },
          {
            label: "省份/地市/区县",
            labelWidth: 130,
            prop: "provinceCityArea",
            type: "cascader",
            props: {
              label: "name",
              value: "code",
            },
            lazy: true,
            async lazyLoad(node, resolve) {
              let stop_level = 2;
              let level = node.level;
              let data = node.data || {};
              let code = data.code;
              let list = [];
              let callback = () => {
                resolve(
                  (list || []).map((ele) => {
                    return Object.assign(ele, {
                      leaf: level >= stop_level,
                    });
                  })
                );
              };
              if (level == 0) {
                await getRegion(code).then(
                  (res) => {
                    list = res.data.data;
                    callback();
                  },
                  (error) => {
                    window.console.log(error);
                  }
                );
              } else if (level == 1) {
                await getRegion(code).then(
                  (res) => {
                    list = res.data.data;
                    callback();
                  },
                  (error) => {
                    window.console.log(error);
                  }
                );
              } else if (level == 2) {
                await getRegion(code).then(
                  (res) => {
                    list = res.data.data;
                    callback();
                  },
                  (error) => {
                    window.console.log(error);
                  }
                );
              } else {
                callback();
              }
            },
            span: 24,
            showColumn: false,
            hide: true,
            rules: [
              {
                required: true,
                message: "请选择省份/地市/区县",
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
          {
            label: "门店地址",
            prop: "address",
            type: "textarea",
            span: 24,
            minRows: 2,
            rules: [
              {
                required: true,
                message: "请输入详细地址",
                trigger: "blur",
              },
            ],
            overHidden: true,
            width: 250,
          },
          {
            label: "负责人",
            prop: "contactName",
            search: true,
            span: 24,
            rules: [
              {
                required: true,
                message: "请输入负责人",
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
          {
            label: "联系方式",
            prop: "contactPhone",
            search: true,
            rules: [
              {
                required: true,
                validator: validatePhone,
                trigger: "blur",
              },
            ],
            overHidden: true,
            minWidth:120
          },
          {
            label: "联系邮箱",
            prop: "email",
            rules: [
              {
                required: true,
                message: "请输入联系邮箱",
                // validator: validatePhone,
                trigger: "blur",
              },
            ],
            overHidden: true,
            minWidth:120
          },
          {
            label: "登录密码",
            prop: "password",
            type: "password",
            span: 12,
            rules: [
              {
                required: true,
                pattern: /^[a-zA-Z0-9]{6,15}$/,
                message: "密码6-15位，由英文、数字组成",
                trigger: "blur",
              },
            ],
            overHidden: true,
            hide: true,
            addDisplay: true,
            editDisplay: false,
            viewDisplay: false,
          },
          {
            label: "确认密码",
            prop: "verifyPassword",
            type: "password",
            span: 12,
            rules: [
              {
                required: true,
                pattern: /^[a-zA-Z0-9]{6,15}$/,
                message: "密码6-15位，由英文、数字组成",
                trigger: "blur",
              },
              {
                required: true,
                validator: validatePass2,
                trigger: "blur",
              },
            ],
            overHidden: true,
            hide: true,
            addDisplay: true,
            editDisplay: false,
            viewDisplay: false,
          },
          //   {
          //     label: "门店状态",
          //     prop: "storeStatusName",
          //     //sortable: true,
          //     slot: true,
          //     display: false,
          //     overHidden:true,
          //   },
          {
            label: "门店状态",
            prop: "storeStatus",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=store_status",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            showColumn: false,
            display: false,
            rules: [
              {
                required: true,
                message: "请输入门店状态",
                trigger: "blur",
              },
            ],
          },
          {
            label: "是否总店",
            prop: "isHeadName",
            //sortable: true,
            slot: true,
            display: false,
            overHidden: true,
          },
        ],
      },
      data: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-merchant/merchant/posStore/pos_store/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
      passwordShow: false,
      passForm: {
        userNo: "",
        password: "",
        checkPass: "",
      },
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.pos_store_add, false),
        viewBtn: this.vaildData(this.permission.pos_store_view, false),
        delBtn: this.vaildData(this.permission.pos_store_delete, false),
        editBtn: this.vaildData(this.permission.pos_store_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  created() {},
  methods: {
    /**
     * @func 门店状态开关
     * @desc 门店状态开关 禁用启用
     * @param {Object} row - 商户信息
     * */
    handleSwitch(row) {
      changeStoreStatus(row.id, row.storeStatus).then(
        () => {},
        (error) => {
          row.storeStatus = row.storeStatus == 1 ? 0 : 1;
          window.console.log(error);
        }
      );
    },
    /**
     * @func 门店管理
     * @desc 门店状态开关 禁用启用
     * @param {Object} row - 商户信息
     * */
    handleStore(row) {
      this.$router.push({
        name: "管理门店",
        query: {
          storeNo: row.rpsNo,
        },
      });
    },
    /* 提交手动修改密码 */
    getPassUpdate() {
      this.$refs["toPassForm"].$refs["passForm"].validate((valid) => {
        if (valid) {
          getUpdatePwd(this.passForm).then(
            (res) => {
              if (res.data.code == "200") {
                this.$message({
                  type: "success",
                  message: "操作成功!",
                });
                this.$refs["toPassForm"].$refs["passForm"].resetFields();
                this.passwordShow = false;
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message,
                });
              }
            },
            (error) => {
              window.console.log(error);
            }
          );
        } else {
          return false;
        }
      });
    },
    /* 修改密码 menu */
    handlePassword(row) {
      console.log(row);
      this.passwordShow = true;
      this.passForm.userNo = row.userNo;
    },
    handlePassClose(done) {
      this.$refs["toPassForm"].$refs["passForm"].resetFields();
      done();
    },
    rowSave(row, done, loading) {
      [row.province, row.city, row.area] = row.provinceCityArea;
      row.rpiNo = this.$route.query.rpiNo;
      // row.storeStatus=0;
      addRpi(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      [row.province, row.city, row.area] = row.provinceCityArea;
      console.log("ROW-", row);
      updateRpi(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.rpsNo).then((res) => {
          this.form = res.data.data;
          this.$nextTick(() => {
            this.form.provinceCityArea = [
              this.form.province,
              this.form.city,
              this.form.area,
            ];
          });
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, { rpiNo: this.$route.query.rpiNo }, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    handleExport() {
      let exQuery = ``;
      exQuery += `&userNo=${this.search.userNo}`;
      exQuery += `&rpiNo=${this.search.rpiNo}`;
      exQuery += `&rpsName=${this.search.rpsName}`;
      exQuery += `&rpsNo=${this.search.rpsNo}`;
      exQuery += `&province=${this.search.province}`;
      exQuery += `&city=${this.search.city}`;
      exQuery += `&area=${this.search.area}`;
      exQuery += `&storeStatus=${this.search.storeStatus}`;
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        window.open(
          `/api/rb-merchant/merchant/posStore/pos_store/export?${
            this.website.tokenHeader
          }=${getToken()}` + exQuery
        );
      });
    },
    handleTemplate() {
      window.open(
        `/api/rb-merchant/merchant/posStore/pos_store/export-template?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  },
};
</script>

<style>
</style>
